package com.gavindon.android.view.education

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.leanback.tab.LeanbackTabLayout
import androidx.leanback.tab.LeanbackViewPager
import androidx.leanback.widget.VerticalGridView
import androidx.viewpager.widget.ViewPager
import com.gavindon.android.R
import com.gavindon.android.adapters.EducationLeftAdapter
import com.gavindon.android.base.BaseActivity
import com.gavindon.android.base.INTENT_FRAGMENT_SMART
import com.gavindon.android.entity.SmartLeftTreeResp
import com.gavindon.android.network.DataResult
import com.gavindon.android.viewmodel.SmartEducationViewModel
import com.google.android.material.tabs.TabLayout
import org.jetbrains.anko.toast


/**
 * description: 智慧教育
 * Created by liNan on  2022-2-6 12:06
 */
class SmartEducationActivity : BaseActivity() {
    override val layoutId = R.layout.activity_smart_education
    private lateinit var mViewPager: LeanbackViewPager
    private lateinit var mTabLayout: LeanbackTabLayout
    private lateinit var leftRv: VerticalGridView
    private lateinit var mViewModel: SmartEducationViewModel
    private lateinit var tvLabel: TextView
    private lateinit var cslEmptyView: ConstraintLayout

    private val courseType: Int by lazy {
        intent.getIntExtra("courseType", 1)
    }
    private val typeName: String by lazy {
        intent.getStringExtra("typeName") ?: ""
    }
    private val frameLayout: FrameLayout by lazy {
        findViewById(R.id.fml_gridview)
    }

    //ViewPagerAdapter
    private var smartEducationViewPagerAdapter: SmartEducationViewPagerAdapter? = null

    override fun onInit(savedInstanceState: Bundle?) {
        mViewPager = findViewById(R.id.lean_view_pager)
        mTabLayout = findViewById(R.id.leanTab)
        leftRv = findViewById(R.id.rvLeft)
        tvLabel = findViewById(R.id.tv_label)
        cslEmptyView = findViewById(R.id.empty_view)
        //初始化viewPagerAdapter
        smartEducationViewPagerAdapter =
            SmartEducationViewPagerAdapter(supportFragmentManager, null)
        //初始化左侧列表
        initLeft()
        mTabLayout.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.action == KeyEvent.ACTION_DOWN) {
                mViewPager.requestFocus()
                return@setOnKeyListener true
            }
            return@setOnKeyListener false
        }
        tvLabel.text = typeName
    }


    fun getLeftView() = leftRv
    fun getTopView() = mTabLayout
    fun getViewPager() = mViewPager

    private fun initLeft() {
        leftRv.setNumColumns(1)
        mViewModel = getViewModel()
        mViewModel.getLeftTree(courseType).observe(this, { resp ->
            if (resp is DataResult.Success) {
                val leftTabList = resp.data.map { it.subjectName }
                val leftAdapter = EducationLeftAdapter(leftTabList)
                leftRv.adapter = leftAdapter
                //当按下遥控右键时
                leftAdapter.setRightFocusChanged {
                    //根据当前页面是viewPager还是frameLayout来切换焦点
                    if (mTabLayout.tabCount > 0) {
                        this.mViewPager.requestFocus()
                    } else {
                        this.frameLayout.requestFocus()
                    }
//
                }
                leftAdapter.setFocusChanged {
                    frameLayout.removeAllViews()
                    val topTabs = resp.data[it].children
                    initTabs(topTabs, resp.data[it])
                }
            }else{
                cslEmptyView.visibility = View.VISIBLE
            }
        })
    }

    /**
     * 动态添加删除View
     * @param topTabs
     */
    private fun initTabs(topTabs: List<SmartLeftTreeResp>, leftTreeResp: SmartLeftTreeResp) {
        //移除之前的tab
        if (mTabLayout.tabCount > 0) {
            mTabLayout.removeAllTabs()
            //必须这样删除tab否则无效
            smartEducationViewPagerAdapter?.setNewTab(null)
            mViewPager.adapter = smartEducationViewPagerAdapter
        }
        //动态添加tab
        if (!topTabs.isNullOrEmpty()) {
            val tabLst = topTabs.map { it.subjectName }
            smartEducationViewPagerAdapter?.setNewTab(topTabs)
            mViewPager.adapter = smartEducationViewPagerAdapter
            mTabLayout.setupWithViewPager(mViewPager)
            tabLst.forEachIndexed { index, s ->
                val tab = mTabLayout.getTabAt(index)
                tab?.let {
                    val customView =
                        layoutInflater.inflate(R.layout.custom_education_tab, null, false)
                    val customTv = customView.findViewById<TextView>(R.id.custom_tab_tv)
                    customTv.text = s
                    tab.customView = customView
                }
            }
        } else {
            initGridView(leftTreeResp)
        }
    }

    private fun initGridView(leftTreeResp: SmartLeftTreeResp) {
        val fragment = EducationFragment()
        fragment.arguments = bundleOf(Pair(INTENT_FRAGMENT_SMART, leftTreeResp))
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fml_gridview, fragment, "gridViewFragment")
        transaction.commitAllowingStateLoss()
    }
}

class SmartEducationViewPagerAdapter(fm: FragmentManager, dataLst: List<SmartLeftTreeResp>?) :
    FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

    private var tabData: List<SmartLeftTreeResp>? = dataLst


    override fun getCount() = tabData?.size ?: 0


    fun setNewTab(tabs: List<SmartLeftTreeResp>?) {
        this.tabData = tabs
        notifyDataSetChanged()
    }


    override fun getItem(position: Int): Fragment {
        val fragment = EducationFragment()
        fragment.arguments =
            bundleOf(Pair(INTENT_FRAGMENT_SMART, tabData?.get(position)), Pair("index", position))
        return fragment
    }

    override fun getPageTitle(position: Int): CharSequence? {
        val tabLst = tabData?.map { it.subjectName }
        return tabLst?.get(position)
    }

}